<?php
// +—————————————————————————————————————————————————————————————————————
// | Created by Yunbao
// +—————————————————————————————————————————————————————————————————————
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +—————————————————————————————————————————————————————————————————————
// | Author: https://gitee.com/yunbaokeji
// +—————————————————————————————————————————————————————————————————————
// | Date: 2022-02-17
// +—————————————————————————————————————————————————————————————————————
class Model_Live extends PhalApi_Model_NotORM {
	/* 创建房间 */
	public function createRoom($uid,$data) {
        
        /* 获取主播 推荐、热门 */
       
		$isexist=DI()->notorm->live
					->select("uid,isvideo,islive")
					->where('uid=?',$uid)
					->fetchOne();

		if($isexist){
            /* 判断存在的记录是否为直播状态 */
            if($isexist['isvideo']==0 && $isexist['islive']==1){
                /* 若存在未关闭的直播 关闭直播 */
                $this->stopRoom($uid,$isexist['stream']);
                
                /* 加入 */
                $rs=DI()->notorm->live->insert($data);
				
            }else{
                /* 更新 */
                $rs=DI()->notorm->live->where('uid = ?', $uid)->update($data);
            }
		}else{
			/* 加入 */
			$rs=DI()->notorm->live->insert($data);
			
		}
		if(!$rs){
			return $rs;
		}

		return 1;
	}
	

	
	/* 修改直播状态 */
	public function changeLive($uid,$stream,$status){

		if($status==1){
            $info=DI()->notorm->live
                    ->select("*")
					->where('uid=? and stream=?',$uid,$stream)
                    ->fetchOne();
            if($info){
                DI()->notorm->live
					->where('uid=? and stream=?',$uid,$stream)
					->update(array("islive"=>1));
            }
			return $info;
		}else{
			$this->stopRoom($uid,$stream);
			return 1;
		}
	}
	

	
	/* 关播 */
	public function stopRoom($uid,$stream) {

		$info=DI()->notorm->live
				->select("uid,showid,starttime,title,province,city,stream,lng,lat,type,type_val,liveclassid,deviceinfo")
				->where('uid=? and stream=? and islive="1"',$uid,$stream)
				->fetchOne();

		if($info){
			$isdel=DI()->notorm->live
				->where('uid=?',$uid)
				->delete();
            if(!$isdel){
                return 0;
            }
			$nowtime=time();
			$info['endtime']=$nowtime;
			$info['time']=date("Y-m-d",$info['showid']);
			$votes=DI()->notorm->user_voterecord
				->where('uid =? and showid=?',$uid,$info['showid'])
				->sum('total');
			$info['votes']=0;
			if($votes){
				$info['votes']=$votes;
			}
			$nums=DI()->redis->zCard('user_'.$stream);			
			DI()->redis->hDel("livelist",$uid);
			DI()->redis->del($uid.'_zombie');
			DI()->redis->del($uid.'_zombie_uid');
			DI()->redis->del('attention_'.$uid);
			DI()->redis->del('user_'.$stream);
			$info['nums']=$nums;			
			$result=DI()->notorm->live_record->insert($info);	

            
		}
		return 1;
	}
	/* 关播信息 */
	public function stopInfo($stream){
		
		$rs=array(
			'nums'=>0,
			'length'=>0,
			'votes'=>0,
		);
		
		$stream2=explode('_',$stream);
		$liveuid=$stream2[0];
		$starttime=$stream2[1];
		$liveinfo=DI()->notorm->live_record
					->select("starttime,endtime,nums,votes")
					->where('uid=? and stream=?',$liveuid,$stream)
					->fetchOne();


		if($liveinfo){
            $cha=$liveinfo['endtime'] - $liveinfo['starttime'];
			$rs['length']=getSeconds($cha,1);
			$rs['nums']=$liveinfo['nums'];
		}
		if($liveinfo['votes']){
			$rs['votes']=$liveinfo['votes'];
		}
		return $rs;
	}
	
	/* 直播状态 */
	public function checkLive($uid,$liveuid,$stream){
        
  

        
		$islive=DI()->notorm->live
					->select("islive,type,type_val,starttime")
					->where('uid=? and stream=?',$liveuid,$stream)
					->fetchOne();
					
		if(!$islive || $islive['islive']==0){
			return 1005;
		}
		$rs['type']=$islive['type'];
		$rs['type_val']='0';
		$rs['type_msg']='';
	


		

		$configpub=getConfigPub();
		
		if($islive['type']==1){
			$rs['type_msg']=md5($islive['type_val']);
			
		}else if($islive['type']==2){

			$rs['type_msg']='本房间为收费房间，需支付'.$islive['type_val'].$configpub['name_coin'];
			$rs['type_val']=$islive['type_val'];
			$isexist=DI()->notorm->user_coinrecord
						->select('id')
						->where('uid=? and touid=? and showid=? and action=6 and type=0',$uid,$liveuid,$islive['starttime'])
						->fetchOne();
			if($isexist){
				$rs['type']='0';
				$rs['type_val']='0';
				$rs['type_msg']='';
			}
		}else if($islive['type']==3){
			$rs['type_val']=$islive['type_val'];
			$rs['type_msg']='本房间为计时房间，每分钟需支付'.$islive['type_val'].$configpub['name_coin'];
		}
		
		return $rs;
		
	}
	
	/* 用户余额 */
	public function getUserCoin($uid){
		$userinfo=DI()->notorm->user
					->select("coin")
					->where('id=?',$uid)
					->fetchOne();
		return $userinfo;
	}
	
	/* 房间扣费 */
	public function roomCharge($uid,$liveuid,$stream){
		$islive=DI()->notorm->live
					->select("islive,type,type_val,starttime")
					->where('uid=? and stream=?',$liveuid,$stream)
					->fetchOne();
		if(!$islive || $islive['islive']==0){
			return 1005;
		}
		
		if($islive['type']==0 || $islive['type']==1 ){
			return 1006;
		}
				
		$total=$islive['type_val'];
		if($total<=0){
			return 1007;
		}
        
        /* 更新用户余额 消费 */
		$ifok=DI()->notorm->user
				->where('id = ? and coin >= ?', $uid,$total)
				->update(array('coin' => new NotORM_Literal("coin - {$total}"),'consumption' => new NotORM_Literal("consumption + {$total}")) );
        if(!$ifok){
            return 1008;
        }

		$action='6';
		if($islive['type']==3){
			$action='7';
		}
		
		$giftid=0;
		$giftcount=0;
		$showid=$islive['starttime'];
		$addtime=time();
		

		/* 更新直播 映票 累计映票 */
		DI()->notorm->user
				->where('id = ?', $liveuid)
				->update( array('votes' => new NotORM_Literal("votes + {$total}"),'votestotal' => new NotORM_Literal("votestotal + {$total}") ));
        
        $insert_votes=[
            'type'=>'1',
            'action'=>$action,
            'uid'=>$liveuid,
            'fromid'=>$uid,
            'actionid'=>$giftid,
            'nums'=>$giftcount,
            'total'=>$total,
            'showid'=>$showid,
            'votes'=>$total,
            'addtime'=>time(),
        ];
        DI()->notorm->user_voterecord->insert($insert_votes);

		/* 更新直播 映票 累计映票 */
		DI()->notorm->user_coinrecord
				->insert(array("type"=>'0',"action"=>$action,"uid"=>$uid,"touid"=>$liveuid,"giftid"=>$giftid,"giftcount"=>$giftcount,"totalcoin"=>$total,"showid"=>$showid,"addtime"=>$addtime ));	
				
		$userinfo2=DI()->notorm->user
					->select('coin')
					->where('id = ?', $uid)
					->fetchOne();	
		$rs['coin']=$userinfo2['coin'];
		return $rs;
		
	}
	

	
	/* 礼物列表 */
	public function getGiftList(){

		$rs=DI()->notorm->gift
			->select("id,type,mark,giftname,needcoin,gifticon,swftime")
			->order("list_order asc,addtime desc")
			->fetchAll();

		return $rs;
	}
	




	/* 赠送礼物 */
	public function sendGift($uid,$liveuid,$stream,$giftid,$giftcount,$touids) {

        /* 礼物信息 */
		$giftinfo=DI()->notorm->gift
					->select("type,mark,giftname,gifticon,needcoin,swftype,swf,swftime")
					->where('id=?',$giftid)
					->fetchOne();
		if(!$giftinfo){
			/* 礼物信息不存在 */
			return 1002;
		}

		$touids_arr=explode(',', $touids);
		if(empty($touids_arr)){
			return 1004;
		}

		$touid_nums=count($touids_arr);
        $personal_total=$giftinfo['needcoin']*$giftcount;
		$total= $personal_total*$touid_nums;

		$total_giftcount=$giftcount*$touid_nums;
		 
		$addtime=time();
		$type='0';
		$action='1';
		
        $stream2=explode('_',$stream);
        $showid=$stream2[1];

	   /* 更新用户余额 消费 */
		$ifok =DI()->notorm->user
				->where('id = ? and coin >=?', $uid,$total)
				->update(array('coin' => new NotORM_Literal("coin - {$total}"),'consumption' => new NotORM_Literal("consumption + {$total}") ) );
		if(!$ifok){
			/* 余额不足 */
			return 1001;
		}


        $multi_arr=[];
        foreach ($touids_arr as $k => $v) {
        	$insert=array(
        		"type"=>$type,
        		"action"=>$action,
        		"uid"=>$uid,
        		"touid"=>$v,
        		"giftid"=>$giftid,
        		"giftcount"=>$giftcount,
        		"totalcoin"=>$personal_total,
        		"showid"=>$showid,
        		"mark"=>$giftinfo['mark'],
        		"addtime"=>$addtime,
        	);
        	$multi_arr[]=$insert;	
        }
            
        DI()->notorm->user_coinrecord->insert_multi($multi_arr); //批量写入

        $gifttoken=md5(md5($action.$uid.$liveuid.$giftid.$giftcount.$total.$showid.$addtime.rand(100,999)));

        $swf=$giftinfo['swf'] ? get_upload_path($giftinfo['swf']):'';

        $result=[];
        $result['gifttoken']=$gifttoken;
        $result['list']=[];

   

        foreach ($touids_arr as $k => $v) {

        	$anthor_total=$personal_total;
        	//获取直播信息


	        // 更新用户 魅力值 累计魅力值
			$istouid =DI()->notorm->user
					->where('id = ?', $v)
					->update( array('votes' => new NotORM_Literal("votes + {$anthor_total}"),'votestotal' => new NotORM_Literal("votestotal + {$personal_total}") ));

			
            $insert_votes=[
                'type'=>'1',
                'action'=>$action,
                'uid'=>$v,
                'fromid'=>$uid,
                'actionid'=>$giftid,
                'nums'=>$giftcount,
                'total'=>$personal_total,
                'showid'=>$showid,
                'votes'=>$anthor_total,
                'addtime'=>time(),
            ];
            DI()->notorm->user_voterecord->insert($insert_votes);
	        

	        // 更新主播热门
	        if($giftinfo['mark']==1){
	            DI()->notorm->live
	                ->where('uid = ?', $v)
	                ->update( array('hotvotes' => new NotORM_Literal("hotvotes + {$personal_total}") ));
	        }


	        $votestotal=$this->getVotes($liveuid);
	        $userinfo2 =DI()->notorm->user
				->select('consumption,coin')
				->where('id = ?', $uid)
				->fetchOne();

			$level=getLevel($userinfo2['consumption']);	

			if($giftinfo['type']!=1){
	            $giftinfo['isplatgift']='0';
	        }

	        $touserinfo=getUserInfo($v);

	        $user_sendgift_info=array(
	            "uid"=>$uid,
	            "touid"=>$v,
	            "to_username"=>$touserinfo['user_nicename'],
	            "giftid"=>$giftid,
	            "type"=>(string)$giftinfo['type'],
	            "mark"=>$giftinfo['mark'],
	            "giftcount"=>$giftcount,
	            "totalcoin"=>$total,
	            "giftname"=>$giftinfo['giftname'],
	            "gifticon"=>get_upload_path($giftinfo['gifticon']),
	            "swftime"=>$giftinfo['swftime'],
	            "swftype"=>$giftinfo['swftype'],
	            "swf"=>$swf,
	            "level"=>$level,
	            "coin"=>$userinfo2['coin'],
	            "votestotal"=>$votestotal,
	
	        );

	        $result['list'][]=$user_sendgift_info;
	        $result['level']=$level;
	        $result['coin']=$userinfo2['coin'];

        }
		

        // 清除缓存
		delCache("userinfo_".$uid); 
		delCache("userinfo_".$liveuid); 	



		return $result;
	}		
	
	/* 发送弹幕 */
	public function sendBarrage($uid,$liveuid,$stream,$giftid,$giftcount,$content) {

		$configpri=getConfigPri();
					 
		$giftinfo=array(
			"giftname"=>'弹幕',
			"gifticon"=>'',
			"needcoin"=>$configpri['barrage_fee'],
		);		
		
		$total= $giftinfo['needcoin']*$giftcount;
		if($total<0){
            return 1002;
        }

        $addtime=time();
        $action='2';

        if($total>0){

        	$type='0';
        	// 更新用户余额 消费
	        $ifok =DI()->notorm->user
	                ->where('id = ? and coin >=?', $uid,$total)
	                ->update(array('coin' => new NotORM_Literal("coin - {$total}"),'consumption' => new NotORM_Literal("consumption + {$total}") ) );
	        if(!$ifok){
	            // 余额不足
	            return 1001;
	        }

	        // 更新直播 魅力值 累计魅力值
	        $istouid =DI()->notorm->user
	                ->where('id = ?', $liveuid)
	                ->update( array('votes' => new NotORM_Literal("votes + {$total}"),'votestotal' => new NotORM_Literal("votestotal + {$total}") ));
	                
	        $stream2=explode('_',$stream);
	        $showid=$stream2[1];
	        if(!$showid){
	            $showid=0;
	        }
	        
	        $insert_votes=[
	            'type'=>'1',
	            'action'=>$action,
	            'uid'=>$liveuid,
	            'fromid'=>$uid,
	            'actionid'=>$giftid,
	            'nums'=>$giftcount,
	            'total'=>$total,
	            'showid'=>$showid,
	            'votes'=>$total,
	            'addtime'=>time(),
	        ];
	        DI()->notorm->user_voterecord->insert($insert_votes);

	        // 写入记录 或更新
	        $insert=array("type"=>$type,"action"=>$action,"uid"=>$uid,"touid"=>$liveuid,"giftid"=>$giftid,"giftcount"=>$giftcount,"totalcoin"=>$total,"showid"=>$showid,"addtime"=>$addtime );
	        $isup=DI()->notorm->user_coinrecord->insert($insert);


        }

        

		$userinfo2 =DI()->notorm->user
				->select('consumption,coin')
				->where('id = ?', $uid)
				->fetchOne();	
			 
		$level=getLevel($userinfo2['consumption']);			
		
		/* 清除缓存 */
		delCache("userinfo_".$uid); 
		delCache("userinfo_".$liveuid); 
		
		$votestotal=$this->getVotes($liveuid);
		
		$barragetoken=md5(md5($action.$uid.$liveuid.$giftid.$giftcount.$total.$showid.$addtime.rand(100,999)));
		 
		$result=array("uid"=>$uid,"content"=>$content,"giftid"=>$giftid,"giftcount"=>$giftcount,"totalcoin"=>$total,"giftname"=>$giftinfo['giftname'],"gifticon"=>$giftinfo['gifticon'],"level"=>$level,"coin"=>$userinfo2['coin'],"votestotal"=>$votestotal,"barragetoken"=>$barragetoken);
		
		return $result;
	}			


    

	
	/* 主播总映票 */
	public function getVotes($liveuid){
		$userinfo=DI()->notorm->user
					->select("votestotal")
					->where('id=?',$liveuid)
					->fetchOne();	
		return $userinfo['votestotal'];					
	}
    

    /* 获取用户本场贡献 */
    public function getContribut($uid,$liveuid,$showid){
        $sum=DI()->notorm->user_coinrecord
				->where('action=1 and uid=? and touid=? and showid=? ',$uid,$liveuid,$showid)
				->sum('totalcoin');
        if(!$sum){
            $sum=0;
        }
        
        return (string)$sum;
    }

    /* 检测房间状态 */
    public function checkLiveing($uid,$stream){
        $info=DI()->notorm->live
                ->select('uid')
				->where('uid=? and stream=? ',$uid,$stream)
				->fetchOne();
        if($info){
            return '1';
        }
        
        return '0';
    }
    
    /* 获取直播信息 */
    public function getLiveInfo($liveuid){
        
        $info=DI()->notorm->live
					->select("uid,title,city,stream,pull,thumb,isvideo,type,type_val,anyway,starttime")
					->where('uid=? and islive=1',$liveuid)
					->fetchOne();
        if($info){
            
            $info=handleLive($info);
            
        }
        
        return $info;
    }


}
